package com.project.util;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    private static final String signKey = "123456wdlhtABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
    private static final Key key = Keys.hmacShaKeyFor(signKey.getBytes());
    private static final Long tokenExpire = 60 * 60 * 1000 * 24L; // 24小时
    public static String createToken(String userName){

        Map<String,Object> claims = new HashMap<>();
        claims.put("userName",userName);
        JwtBuilder jwtBuilder = Jwts.builder();
        jwtBuilder.claims(claims);
        jwtBuilder.signWith(key, SignatureAlgorithm.HS256); //签发算法，秘钥为jwtToken
        jwtBuilder.issuedAt(new Date()); //设置当前token签发时间
        jwtBuilder.expiration(new Date(System.currentTimeMillis()+tokenExpire));
        String token = jwtBuilder.compact();
        return token;
    }
    /**
     * 验证token的合法性
     * */
    public static Map<String,Object> checkToken(String token){
        Map<String,Object> tokenPayload = null;
        try {
            Jwt parse = Jwts.parser().setSigningKey(key).build().parse(token);
            tokenPayload = (Map<String, Object>) parse.getPayload();
        }catch (Exception e){
            e.printStackTrace();
        }
        return tokenPayload;
    }


}
